package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"os/signal"
	"strings"
	"syscall"
	"time"

	"gin-gateway/core/init"
)

// gateway 以它为前缀从 etcd 获取服务列表
var serviceName = "test_strip_uri"

func main() {
	// 环境变量中格式为 "httpbackend1,2003,50"
	// 分别为：k8s 中的 service 名、pod 监听端口、权重
	sc1 := strings.Split(os.Getenv("BACKEND_SCHEME_1"), ",")
	if len(sc1) != 3 {
		log.Fatal("BACKEND_SCHEME should be set")
	}

	rs1 := &RealServer{Addr: fmt.Sprintf("0.0.0.0:%s", sc1[1])}
	rs1.Run()

	etcdServer := os.Getenv("ETCD_SERVER")
	if len(etcdServer) == 0 {
		log.Fatal("ETCD_SERVER should be set")
	}
	registry, err := Init.NewEtcdRegistry([]string{etcdServer}, time.Duration(5))
	if err != nil {
		log.Fatal(err)
	}

	// 注册格式：
	// key 为："test_strip_uri:2003"
	// value 为 "httpbackend1:2003,50"
	backend1 := fmt.Sprintf("%s/%s", serviceName, sc1[1])
	registry.Register(backend1, fmt.Sprintf("%s:%s,%s", sc1[0], sc1[1], sc1[2]))

	//监听关闭信号
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	rs1.Close()
	err = registry.Unregister(context.Background(), backend1)
	if err != nil {
		fmt.Println("unregister")
		panic(err)
	}
	fmt.Printf("close server: %s", rs1.Addr)

	err = registry.Close()
	if err != nil {
		panic(err)
	}
}

type RealServer struct {
	Addr   string
	server *http.Server
}

func (r *RealServer) Run() {
	log.Println("Starting httpserver at " + r.Addr)
	mux := http.NewServeMux()
	mux.HandleFunc("/", r.HelloHandler)
	mux.HandleFunc("/error", r.ErrorHandler)
	mux.HandleFunc("/timeout", r.TimeoutHandler)
	r.server = &http.Server{
		Addr:         r.Addr,
		WriteTimeout: time.Second * 3,
		Handler:      mux,
	}
	go func() {
		r.server.ListenAndServe()
	}()
}
func (r *RealServer) Close() {
	r.server.Close()
}

func (r *RealServer) HelloHandler(w http.ResponseWriter, req *http.Request) {
	//127.0.0.1:8008/abc?sdsdsa=11
	//r.Addr=127.0.0.1:8008
	//req.URL.Path=/abc
	//fmt.Println(req.Host)
	upath := fmt.Sprintf("http://%s%s\n", r.Addr, req.URL.Path)
	realIP := fmt.Sprintf("RemoteAddr=%s,X-Forwarded-For=%v,X-Real-Ip=%v\n", req.RemoteAddr, req.Header.Get("X-Forwarded-For"), req.Header.Get("X-Real-Ip"))
	header := fmt.Sprintf("headers =%v\n", req.Header)
	io.WriteString(w, upath)
	io.WriteString(w, realIP)
	io.WriteString(w, header)

}

func (r *RealServer) ErrorHandler(w http.ResponseWriter, req *http.Request) {
	upath := "error handler"
	w.WriteHeader(500)
	io.WriteString(w, upath)
}

func (r *RealServer) TimeoutHandler(w http.ResponseWriter, req *http.Request) {
	time.Sleep(6 * time.Second)
	upath := "timeout handler"
	w.WriteHeader(200)
	io.WriteString(w, upath)
}
